package com.zhiyou.app.common.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zhiyou.app.pojo.entity.BaseEntity;
import com.zhiyou.app.pojo.enums.DeletedEnum;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author : bind
 * @Date : 2022-06-14 14:41
 */
@Component
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("deleted", DeletedEnum.NO_DELETED.code, metaObject);

        if (metaObject.getOriginalObject() instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) metaObject.getOriginalObject();
            if (ObjectUtil.isEmpty(entity.getCreateTime())) {
                this.setFieldValByName("createTime", DateUtil.date().toJdkDate(), metaObject);
            }
            if (ObjectUtil.isEmpty(entity.getUpdateTime())) {
                this.setFieldValByName("updateTime", DateUtil.date().toJdkDate(), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", DateUtil.date().toJdkDate(), metaObject);
    }

}
